<?php
declare (strict_types=1);

namespace app\command;

use app\common\model\Member;
use ShidianUtil\Api\Tencent\Wechat\Wechat;
use think\Collection;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class WechatSubscription extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('ws')
            ->setDescription('the Wechat Subscription command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('同步律师关注情况');

        $member = Member::getTable();

        Member::tableField(['id', 'openidWechat'], $member)
            ->where('type', '1')
            // ->where('phone', '18380335706')
            ->where('openidWechat', '<>', '')
            ->chunk(1000, function (Collection $collection) {

                $collection->each(function (Member $member) {

                    $response = $this->getWechat()
                        ->subscription(SUBSCRIPTION)
                        ->user()
                        ->info($member->openidWechat);

                    if (!$response->isSuccess()) {
                        return;
                    }

                    $decodeContents = $response->getDecodeContents();

                    if (!isset($decodeContents['subscribe'])) {
                        return;
                    }

                    $subscribe = $decodeContents['subscribe'];

                    if ($subscribe != $member->followedWechat) {
                        $member->followedWechat = $subscribe;
                        $member->save();
                    }

                });
            });

        $output->writeln('完成');
    }

    private function getWechat(): Wechat
    {
        return app(Wechat::class);
    }
}
